Data Types and Variables

Variables#

A variable is simply a name to which a value can be assigned.

The simplest way to assign a value to a variable is through the = operator. Variables allow us to store data so that we can use it later to perform operations in the code.

svg viewer

Data Types#

Python provides three main data types:

  • Numbers
  • Strings
  • Booleans

Let’s cover these in detail below:

Numbers#

There are three main types of numbers in Python:

  • Integers
  • Floating Point Numbers
  • Complex Numbers

Integers#

The integer data type can hold positive and negative whole numbers.

Floating point number#

Floating point numbers, or floats, refer to positive and negative numbers with a fractional part.

Complex numbers#

Python also supports complex numbers. There are two ways to create a complex number:

  1. complex() is used to create complex numbers. The first argument is the real part and the second argument is the imaginary part.
  2. Simply write the value as x+yj, where x is the real part and y is the complex part and j represents the iota.
Extracting real and imaginary#
  • To extract the real part of a complex number, we use .real.
z.real
  • To extract the imaginary part of a complex number, we use .imag.
z.imag

Let’s look at an example of this below:

Booleans#

The Boolean (also known as bool) data type allows us to choose between two values: true and false. In Python, we can simply use True or False to represent a bool:

Booleans are often used in data comparisons.

Strings#

A string is a collection of characters enclosed within single or double quotation marks.

Length of a string#

The length of a string can be found using the len() function.

Indexing#

A string in Python is indexed from 0 to n-1 where n is its length. This means that the index of the first character in a string is 0. Each character in a string can be accessed using its index. The index must be closed within square brackets, [].

svg viewer

We’ll learn about operators in the next lesson.

About This Course

Operators